// pages/editor-userinfo/editor.js
var grade = require('../grade/model/GradeModel.js')
var userModel=require('../my/model/UserModel.js')
var loginModel = require('../login/model/loginModel.js')
var bottomAnimation = wx.createAnimation({
  duration: 300,
  timingFunction: 'linear',
  height: 0,
  top: 0,
  bottom: 0,
  right: 0,
  backgroundColor: '#fff',
  opcity: 0.6
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user:{},
    updateInfo: { iconBit: '', userName: '', userSex: '', birthDate:'',gradeLevel: '', des:''},
    sexlist:[{id:0,text:'女'},{id:1,text:'男'}],
    sexIndex:0,
    _hasChangeInfo:false,//是否有改动信息
    _currentInputTip:'',
    _currentInputFiledName:'',//当前修改用户信息属性名称
    _currentTextAreaInputValue:'',
    gradeList:[],
    gradeIndex:0
  },
  textareaInput:function(event){
    this.setData({
      _currentTextAreaInputValue: event.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    var currentUserInfo = getApp().globalData.userInfo
    var sex = currentUserInfo.userSex;
    var _sexIndex=0;//让picker自动选中
    this.data.sexlist.forEach(function(item,index){
      if (item.id == sex){
        _sexIndex=index
      }
    })
    var _gradeIndex=0;
    this.getGradeList(function(list){
      list.forEach(function(item,index){
        if (item.gradeId == currentUserInfo.gradeLevel){
          _gradeIndex=index
          that.setData({
            gradeIndex: _gradeIndex
          })
        }
      })
    })
    this.setData({
      user: currentUserInfo,
      sexIndex: _sexIndex
    })
  },
  //绑定微信
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      wx.login({
        success: function (res) {
          //插入登录的用户的相关信息到数据库
          loginModel.requestwxbd("xcx", res.code, function (data) {
            var _openId = data.openId
            app.globalData.userInfo = data
            app.globalData.openId = _openId
            wx.switchTab({
              // url: '../index/index',
            })
          })
        }
      });

    }
    else {
      wx.showToast({
        title: "您点击了拒绝授权，将无法完成绑定",
        icon: 'none',
      })
      return
    }
  },


  //点击选择用户头像
  changeHeaderIcon: function (event) {
    var that=this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        var fileSize=res.tempFiles[0].size/1024
        wx.getImageInfo({
          src: tempFilePaths[0],
          success: function (res) {
            that.setData({
              cWidth: res.width,
              cHeight: res.height,
              _hasChangeInfo:true
            })
            //大于100k压缩
            if (Number(fileSize)>100){
              console.log("image start compresse...")
              var rate = 0.5;
              if (Number(fileSize) > 300 && Number(fileSize)<=500){
                rate=0.3
              } else if (Number(fileSize)>500){
                rate = 0.2
              }
              that.getCanvasImg(tempFilePaths[0], res.width, res.height, rate, function (result) {
                that.setData({
                  ['user.userIcon']: result.tempFilePath
                })
                that.transformBase(result.tempFilePath)
              });
            }else{
              that.setData({
                ['user.userIcon']: tempFilePaths[0]
              })
              that.transformBase(tempFilePaths[0])
            }
          },
        })
      }
    })
  },

  reStoreData(){
    getApp().globalData.userInfo=this.data.user
    this.setData({
      updateInfo: { iconBit: '', userName: '', userSex: '', gradeLevel: '', des: '' },
      _hasChangeInfo:false,
      _currentInputTip:'',
      _currentInputFiledName:'',
      _currentTextAreaInputValue:''
    })
  },
  changeUserName: function (event) {
    this.setData({
      _currentInputFiledName:'userName',
      _currentInputTip:"请输入用户名"
    })
    _openBottomAnimation(this)
  },
  //性别选择
  sexSelected:function(event){
    var sexListIndex=event.detail.value
    var sex=this.data.sexlist[sexListIndex]
    this.setData({
      sexIndex: sexListIndex,
      ['user.userSex']: sex.id,
      ['updateInfo.userSex']: sex.id,
      _hasChangeInfo:true
    })
  },
  //年级选择
  changeUserLevel: function (event) {
    var gradeListIndex = event.detail.value
    var grade = this.data.gradeList[gradeListIndex]
    this.setData({
      gradeIndex: gradeListIndex,
      ['user.gradeLevel']: grade.gradeId,
      ['user.gradeLevelText']: grade.gradeText,
      ['updateInfo.gradeLevel']: grade.gradeId,
      _hasChangeInfo: true
    })
  },
  changeUserDes: function (event) {
    this.setData({
      _currentInputFiledName: 'des',
      _currentInputTip: "请输入您的介绍"
    })
    _openBottomAnimation(this)
  },
  getGradeList(loadCallBack){
    var that=this
    var grades = wx.getStorageSync("grades")
    if (grades != null && grades != undefined && grades.length > 0) {
      that.setData({
        gradeList: grades
      })
      loadCallBack(grades)
    } else {
      grade.getGradeList(function (list) {
        wx.setStorage({
          key: 'grades',
          data: list,
        })
        that.setData({
          gradeList: list
        })
        loadCallBack(list)
      })
    }
  },
    transformBase(path) {
    let that = this;
    var FSM = wx.getFileSystemManager();
    FSM.readFile({
      filePath: path,
      encoding: "base64",
      success: function (data) {
        that.setData({
          ['updateInfo.iconBit']: data.data
        })
      }
    });
  },
  /**
   * 质量压缩
   */
  getCanvasImg(imagePath, canvasWidth, canvasHeight, quality, callback) {
    var that = this;
    const ctx = wx.createCanvasContext('attendCanvasId');
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.drawImage(imagePath, 0, 0, canvasWidth, canvasHeight);
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'attendCanvasId',
        fileType: 'jpg',
        quality: quality,
        success: function success(res) {
          callback && callback(res)
        }, fail: function (e) {
          console.log(e)
        }
      });
    });
  },
  closeAnimation: function (event) {
    console.log("close")
    _closeBottomAnimation(this)
  },
  //输入确定
  submitInput: function (event) {
    _closeBottomAnimation(this)
    var value = event.detail.value.inputValue
    if (value == null || value == undefined || value.length <= 0) {
      return
    }
    var obj = this.data.updateInfo
    for (var key in obj) {
      if (key == this.data._currentInputFiledName) {
        obj[key] = value
      }
    }
    var user = this.data.user;
    var _currentUpdateFiled = 'this.data._currentInputFiledName';
    for (var field in user) {
      var tempFiledName = field.toLowerCase()
      if (tempFiledName == this.data._currentInputFiledName.toLowerCase()
        || tempFiledName.indexOf(this.data._currentInputFiledName.toLowerCase()) != -1) {
        _currentUpdateFiled = field
        break
      }
    }
    this.setData({
      updateInfo: obj,
      ['user.' + _currentUpdateFiled]: value,
      _currentInputFiledName: '',
      _currentTextAreaInputValue: '',
      _hasChangeInfo: true
    })
  },
  //保存用户信息
  saveUserInfo: function (event) {
    var that = this
    if (this.data.updateInfo.gradeLevel == null || this.data.updateInfo.gradeLevel == ""){
      this.data.updateInfo.gradeLevel=this.data.user.gradeLevel;
    }
    console.log(this.data.updateInfo)
    userModel.saveUserInfo(this.data.updateInfo, function () {
      that.reStoreData()
      wx.showToast({
        title: '更新成功',
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
function _openBottomAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(-90 + 'vh').step()
  context.setData({
    animationData: animation.export(),
    bottomViewShow: true,
  })
}
function _closeBottomAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(90 + 'vh').step()
  context.setData({
    animationData: animation.export(),
    bottomViewShow: false,
  })
}